/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lomtools.services;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Leonardo Oliveira Moreira
 *
 * Servlet genérico
 */
public abstract class GenericService extends HttpServlet {

    /**
     * Método estático utilizado para salvar os parâmetros passado pelo usuário do serviço
     * 
     * @param request
     * @param response
     */
    public static void saveParameters(HttpServletRequest request, HttpServletResponse response) {
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames != null && parameterNames.hasMoreElements()) {
            String parameter = (String) parameterNames.nextElement();
            if (parameter != null && parameter.trim().length() > 0) {
                String result = request.getParameter(parameter);
                if (result != null && result.trim().length() > 0) {
                    request.setAttribute(parameter, result);
                }
            }
        }
    }

    /**
     * Método estático utilizado para remover os atributos salvos no objeto de requisição
     * 
     * @param request
     * @param response
     */
    public static void removeAttributes(HttpServletRequest request, HttpServletResponse response) {
        Enumeration attributeNames = request.getAttributeNames();
        while (attributeNames != null && attributeNames.hasMoreElements()) {
            String attribute = (String) attributeNames.nextElement();
            if (attribute != null && attribute.trim().length() > 0 && ! attribute.equals("message")) {
                Object result = request.getAttribute(attribute);
                if (result != null && result instanceof String && ((String) result).trim().length() > 0) {
                    request.removeAttribute(attribute);
                }
            }
        }
    }

    /**
     * Método abstrato que é utilizado para implementar o serviço
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException;
    
    public void setMessage(HttpServletRequest request, String message) {
        request.setAttribute("message", message);
    }

}
